﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.InforWebService;
using System.Text.RegularExpressions;
using System.IO;
using SalaryChannel.ReportService;
namespace SalaryChannel
{
    public partial class InforCollectCtrl : UserControl
    {
        public InforCollectCtrl()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(InforCollectCtrl_Loaded);
        }

        void InforCollectCtrl_Loaded(object sender, RoutedEventArgs e)
        {
            ServiceInstance.InforService.GetValidTaskCompleted += new EventHandler<GetValidTaskCompletedEventArgs>(InforService_GetValidTaskCompleted);
            ServiceInstance.InforService.GetColumnFromTableByTaskIDCompleted += new EventHandler<GetColumnFromTableByTaskIDCompletedEventArgs>(InforService_GetColumnFromTableByTaskIDCompleted);
            ServiceInstance.InforService.InsertValuesCompleted += new EventHandler<InsertValuesCompletedEventArgs>(InforService_InsertValuesCompleted);
            ServiceInstance.InforService.ExportInfoIntoFileCompleted += new EventHandler<ExportInfoIntoFileCompletedEventArgs>(InforService_ExportInfoIntoFileCompleted);
            ServiceInstance.InforService.ExportInfoIntoStringCompleted += new EventHandler<ExportInfoIntoStringCompletedEventArgs>(InforService_ExportInfoIntoStringCompleted);

            SearchStartDPicker.Text = DateTime.Now.ToShortDateString();
            SearchEndDPicker.Text = SearchStartDPicker.Text;
        }

      

        

        /// <summary>
        /// 初始化
        /// </summary>
        public void Initiallize()
        {
           
            TaskConfigPage.Visibility = App.IsAuth(7) ? Visibility.Visible : Visibility.Collapsed;
            CurrentTask = null;
            this.MyTaskGrid.ItemsSource = null;
            this.OneRowGrid.ItemsSource = null;
            this.DownloadBtn.Visibility = Visibility.Collapsed;
            this.Grid3.ItemsSource = null;
            this.BigTab.SelectedIndex = 0;
            this.TaskTitle2.Text = "请选择一个任务";

          

        }


        /// <summary>
        /// 选择Tab页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BigTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((sender as TabControl).SelectedItem != null)
            {
                if ((sender as TabControl).SelectedIndex == 1)
                {
                    InitInforCommitPage();
                }
                else  if ((sender as TabControl).SelectedIndex ==2)
                {
                    if (CurrentTask != null)
                    {
                        this.TaskTitle2.Text = CurrentTask.Name;
                        DownloadBtn.Visibility = Visibility.Collapsed;
                    }
                }
                else if((sender as TabControl).SelectedIndex ==3)
                {
                    InitTaskConfigPage();
                }

            }
        }

        #region 任务列表

        private VW_ValidTask _currentTask = null;
        private VW_ValidTask CurrentTask
        {
            get
            {
                return _currentTask;
            }
            set
            {
                if (_currentTask != value)
                {
                    _currentTask = value;
                    this.CurrentTaskTB.Text = _currentTask == null ? string.Empty : _currentTask.Name;
                }
            }
        }

        /// <summary>
        /// 查询任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ServiceInstance.InforService.GetValidTaskAsync(TaskNameTB.Text.Trim());
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败", Title.Error);
                     
            }
        }
        void InforService_GetValidTaskCompleted(object sender, GetValidTaskCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询结果无效，请稍后重试！", Title.Error);
                }
                else
                {
                    this.MyTaskGrid.ItemsSource = e.Result;
                }
            }
            catch
            {
                
               App.MessageBox.ShowDialog("查询结果无效，请稍后重试！", Title.Error);
            }
        }

        private void MyTaskGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.MyTaskGrid.SelectedItem != null)
            {
                this.CurrentTask = this.MyTaskGrid.SelectedItem as VW_ValidTask;
            }
        }
        #endregion

        #region 提交信息
        private void InitInforCommitPage()
        {
            if (CurrentTask == null)
            {
                return;
            }
            //更换任务后要初始化界面
            if (this.InforCommitPage.Tag == null
                || !InforCommitPage.Tag.Equals(CurrentTask.ID))
            {
                this.TaskTitle.Text = CurrentTask.Name;
                this.InforCommitPage.Tag = CurrentTask.ID;
                try
                {
                    ServiceInstance.InforService.GetColumnFromTableByTaskIDAsync(CurrentTask.ID);
                }
                catch 
                {
                    App.MessageBox.ShowDialog("查询数据列失败，请稍后再试！", Title.Error);
                }
            }
            
        }
        void InforService_GetColumnFromTableByTaskIDCompleted(object sender, GetColumnFromTableByTaskIDCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询数据列失败，结果无效", Title.Error);
                }
                else
                {
                    OneRowGrid.ItemsSource = e.Result;

                  
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog("查询数据列失败，结果无效", Title.Error);
            }
        }

        private void DemoFileBtn_Click(object sender, RoutedEventArgs e)
        {

            if (OneRowGrid.ItemsSource == null)
            {
                App.MessageBox.ShowDialog("获取表字段信息失败", Title.Error);
            }
            else
            {
                SaveFileDialog fDialog = new SaveFileDialog();
                fDialog.Filter = "文本文件(*.txt)|*.txt";
                if (fDialog.ShowDialog().Value)
                {
                    try
                    {
                        string header = string.Empty;
                        foreach (SP_GetColFromTableResult sp in (OneRowGrid.ItemsSource as List<SP_GetColFromTableResult>))
                        {
                            header += (sp.ColName + "\t");
                        }
                        TextWriter writer = new StreamWriter(fDialog.OpenFile(), System.Text.Encoding.UTF8);
                        writer.WriteLine(header.Trim());
                        writer.Flush();
                        writer.Close();
                        writer.Dispose();
                        App.MessageBox.ShowDialog("保存成功", Title.Information);
                    }
                    catch (Exception ex)
                    {
                        App.MessageBox.ShowDialog("保存文件失败：" + ex.Message, Title.Error);

                    }
                }
            }
        }


        private static Regex DateRegex = new Regex( @"^(?:((((0[0-9])(([02468][48])|([13579][26]))-0?2-29))|(((0[0-9])(([2468][048])|([13579][26]))-0?2-29))|(((0[1-9])(([02468][048])|([13579][26]))-0?2-29))|((([1-9][0-9])(([02468][048])|([13579][26]))-0?2-29))|((0[0-9][0-9][1-9])|(0[0-9][1-9][0-9])|(0[1-9][0-9][0-9])|([1-9][0-9][0-9][0-9]))-((((0?[1-9])|(1[0-2]))-((0?[1-9])|(1[0-9])|(2[0-8])))|((((0?[13578])|(1[02]))-31)|(((0?[1,3-9])|(1[0-2]))-(29|30))))))$");
        private static Regex DigitalRegex = new Regex(@"^\d+$");
        private static Regex FloatRegex = new Regex(@"^(\d+\.\d+)|(\d+)$");

        private void CmtInputBtn_Click(object sender, RoutedEventArgs e)
        {
            string insertString = string.Empty;
            foreach (SP_GetColFromTableResult sp in (OneRowGrid.ItemsSource as List<SP_GetColFromTableResult>))
            {
                if (sp.IsNullable == true
                    && string.IsNullOrEmpty(sp.ColData.Trim()))
                {
                   // App.MessageBox.ShowDialog(sp.ColName + " 不能为空",Title.Warning);
                    insertString +="null,";
                }
                else if (sp.TypeName == "int")
                {
                    if (!DigitalRegex.IsMatch(sp.ColData))
                    {
                        App.MessageBox.ShowDialog(sp.ColName + " 必须是整数", Title.Warning);
                        return;
                    }
                    insertString += sp.ColData + ",";
                }
                else if (sp.TypeName.Contains("char"))
                {
                    if (sp.ColData.Length> sp.ColLength)
                    {
                        App.MessageBox.ShowDialog(sp.ColName + " 长度超过规定值["+sp.ColLength.ToString()+"]", Title.Warning);
                        return;
                    }
                    insertString += "\'" + sp.ColData + "\',";
                }
                else if (sp.TypeName == "datetime")
                {
                    if (!DateRegex.IsMatch(sp.ColData))
                    {
                        App.MessageBox.ShowDialog(sp.ColName + " 格式不正确，应为YYYY-MM-DD", Title.Warning);
                        return;
                    }
                    insertString += "\'" + sp.ColData + "\',";
                }
                else if (sp.TypeName == "float")
                {
                    if (!FloatRegex.IsMatch(sp.ColData))
                    {
                        App.MessageBox.ShowDialog(sp.ColName + " 必须是小数，不能有百分号", Title.Warning);
                        return;
                    }
                    insertString += sp.ColData + ",";
                }
               
            }
            insertString = insertString.Remove(insertString.Length - 1);

            try
            {
                CmtInputBtn.IsEnabled = false;
                ServiceInstance.InforService.InsertValuesAsync(insertString, CurrentTask.ID, App.CurrentUser.UserID, -1);
            }
            catch
            {
                CmtInputBtn.IsEnabled = true;
                App.MessageBox.ShowDialog("连接服务器失败", Title.Error);
            }
        }
        void InforService_InsertValuesCompleted(object sender, InsertValuesCompletedEventArgs e)
        {
            

            try
            {
                if (e.Cancelled)
                {
                    App.MessageBox.ShowDialog("提交数据返回失败", Title.Error);
                }
                else
                {
                    if (e.UserState.Equals(-1))
                    {
                        CmtInputBtn.IsEnabled = true;
                        if (e.Result)
                        {
                           
                            App.MessageBox.ShowDialog("提交成功");
                            ClearBtn_Click(null, null);
                        }
                        else
                        {
                            App.MessageBox.ShowDialog("提交数据返回失败", Title.Error);
                        }
                    }
                    else
                    {
                       
                        int index = int.Parse(e.UserState.ToString());
                         if (!e.Result)
                        {
                            ErrorRows.Add(ReadyRows[index]);
                        }

                        if (index < ReadyRows.Count - 1)
                        {
                            ServiceInstance.InforService.InsertValuesAsync(ReadyRows[index + 1], CurrentTask.ID,
                                App.CurrentUser.UserID, index + 1);
                        }
                        else
                        {
                            ImportBtn.IsEnabled = true;
                            importLoading.Stop();
                            if (ErrorRows.Count == 0)
                            {
                                ErrorBtn.IsEnabled = false;
                                App.MessageBox.ShowDialog("全部提交成功");

                            }
                            else
                            {
                                ErrorBtn.IsEnabled = true;
                                App.MessageBox.ShowDialog("部分数据失败");

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
                 App.MessageBox.ShowDialog("提交数据返回失败,"+ex.Message, Title.Error);
            }
        }

        private void ClearBtn_Click(object sender, RoutedEventArgs e)
        {
            foreach (SP_GetColFromTableResult sp in (OneRowGrid.ItemsSource as List<SP_GetColFromTableResult>))
            {
                sp.ColData = string.Empty;
            }
        }

        private FileInfo dataFI = null;
        private void ChooseFileBtn_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fDialog = new OpenFileDialog();
            fDialog.Filter = "文本文件(*.txt)|*.txt";
            fDialog.Multiselect = false;
            if (fDialog.ShowDialog().Value)
            {
                try
                {

                    this.FileTB.Text = fDialog.File.Name;
                    dataFI = fDialog.File;

                }
                catch (Exception ex)
                {
                    App.MessageBox.ShowDialog("选择数据文件失败：" + ex.Message, Title.Error);

                }
            }
        }

        List<string> ErrorRows = new List<string>();
        List<string> ReadyRows = new List<string>();
        private void ImportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ErrorRows.Count > 0)
            {
                ErrorRows.Clear();
            }
            if (ReadyRows.Count > 0)
            {
                ReadyRows.Clear();
            }
            using (StreamReader reader = dataFI.OpenText())
            {// 

                string line = string.Empty;
                try
                {
                    List<SP_GetColFromTableResult> Columns = OneRowGrid.ItemsSource as List<SP_GetColFromTableResult>;
                     
                    //首行
                    while (!reader.EndOfStream)
                    {
                        line = reader.ReadLine();
                        if (string.IsNullOrEmpty(line))
                        {
                            continue;
                        }
                        string[] colHeaders = line.Split(new char[]{'\t'});
                        if(colHeaders.Length != Columns.Count)
                        {
                            App.MessageBox.ShowDialog("源文件中第一行的列数与要求的列数不一致");
                            return;
                        }
                        int i;
                        for (i= 0; i < colHeaders.Length; i++)
                        {
                            if (colHeaders[i] != Columns[i].ColName)
                            {
                               System.Windows.MessageBox.Show(string.Format("源文件中第一行的列名[{0}]与要求的列名[{1}]不一致",colHeaders[i],Columns[i].ColName),
                                   "提示", MessageBoxButton.OK);
                                return;
                            }
                        }
                        break;
                    }
                    //数据行
                    while (!reader.EndOfStream)
                    {
                        line = reader.ReadLine();
                        if (string.IsNullOrEmpty(line))
                        {
                            continue;
                        }
                        string insertString = string.Empty;
                        string[] colHeaders = line.Split(new char[] { '\t' });
                        if (colHeaders.Length != Columns.Count)
                        {
                            ErrorRows.Add(line);
                            continue;
                        }

                        int i;
                        bool bFormated = true;
                        for (i = 0; i < Columns.Count; i++)
                        {
                            
                            if (Columns[i].IsNullable == true
                                 && string.IsNullOrEmpty(colHeaders[i].Trim()))
                            {
                                // App.MessageBox.ShowDialog(Columns[i].ColName + " 不能为空",Title.Warning);
                                insertString += "null,";
                            }
                            else if (Columns[i].TypeName == "int")
                            {
                                if (!DigitalRegex.IsMatch(colHeaders[i]))
                                {
                                    bFormated = false;
                                    continue;
                                }
                                insertString += colHeaders[i] + ",";
                            }
                            else if (Columns[i].TypeName.Contains("char"))
                            {
                                if (colHeaders[i].Length > Columns[i].ColLength)
                                {
                                    bFormated = false;
                                    continue;
                                }
                                insertString += "\'" + colHeaders[i] + "\',";
                            }
                            else if (Columns[i].TypeName == "datetime")
                            {
                                if (!DateRegex.IsMatch(colHeaders[i]))
                                {
                                    bFormated = false;
                                    continue;
                                }
                                insertString += "\'" + colHeaders[i] + "\',";
                            }
                            else if (Columns[i].TypeName == "float")
                            {
                                if (!FloatRegex.IsMatch(colHeaders[i]))
                                {
                                    bFormated = false;
                                    continue;
                                }
                                insertString += colHeaders[i] + ",";
                            }
                        }
                        if ( bFormated ==false)
                        {

                            ErrorRows.Add(line);
                            continue;
                        } 
                        insertString = insertString.Remove(insertString.Length - 1);


                        ReadyRows.Add(insertString);
                      

                    }
                    reader.Close();
                    reader.Dispose();

                   
                }
                catch(Exception ex)
                {
                    App.MessageBox.ShowDialog("读取数据失败，"+ex.Message, Title.Error);
                    ErrorRows.Clear();
                    ReadyRows.Clear();
                    return;
                }
                if (ReadyRows.Count == 0)
                {
                    App.MessageBox.ShowDialog("读取数据失败，无有效数据", Title.Error);
                    ErrorRows.Clear();
                    ReadyRows.Clear();
                    return;
                }
                try
                {
                    ServiceInstance.InforService.InsertValuesAsync(ReadyRows[0], CurrentTask.ID, App.CurrentUser.UserID, 0);
                    importLoading.Show();
                    ImportBtn.IsEnabled = false;
                }
                catch
                {
                    importLoading.Stop();
                    ImportBtn.IsEnabled = true;
                    App.MessageBox.ShowDialog("连接服务器失败", Title.Error);
                    
                }
            }
        }

        private void ErrorBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ErrorRows.Count == 0)
            {
                App.MessageBox.ShowDialog("没有失败记录");
            }
            else
            {
                SaveFileDialog fDialog = new SaveFileDialog();
                fDialog.Filter = "文本文件(*.txt)|*.txt";
                if (fDialog.ShowDialog().Value)
                {
                    try
                    {
                        using (StreamWriter writer = new StreamWriter(fDialog.OpenFile(), System.Text.Encoding.UTF8))
                       // using (StreamWriter writer = new StreamWriter(fDialog.SafeFileName, false, System.Text.Encoding.UTF8))
                        {
                            foreach (string s in ErrorRows)
                            {
                                writer.WriteLine(s);
                            }
                        }

                        App.MessageBox.ShowDialog("导出成功", Title.Information);
                    }
                    catch (Exception ex)
                    {
                        App.MessageBox.ShowDialog("导出失败：" + ex.Message, Title.Error);

                    }
                }
            }
        }
        #endregion       
       

        #region 信息查询

        private void ExportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentTask == null
                || string.IsNullOrEmpty(SearchStartDPicker.Text)
                || string.IsNullOrEmpty(SearchEndDPicker.Text))
            {
                return;
            }
            
            if (DateTime.Parse(SearchStartDPicker.Text) >= DateTime.Parse(SearchEndDPicker.Text))
            {

                App.MessageBox.ShowDialog("开始日期应小于结束日期");
                return;
            }
            try
            {
                ServiceInstance.InforService.ExportInfoIntoFileAsync(CurrentTask.ID,
                       App.CurrentUser.UserID,
                       SearchStartDPicker.Text,
                       SearchEndDPicker.Text);
                exportLoading.Show();
            }
            catch(Exception ex)
            {

                App.MessageBox.ShowDialog("提交失败，"+ex.Message);
            }

        }

        void InforService_ExportInfoIntoFileCompleted(object sender, ExportInfoIntoFileCompletedEventArgs ee)
        {
            try
            {
                exportLoading.Stop();
                ExportBtn.IsEnabled = true;
                if (ee.Result == string.Empty)
                {
                    App.MessageBox.ShowDialog("没有查询到数据");
                }
                else if (ee.Result =="-1")
                {
                    App.MessageBox.ShowDialog("导出失败，请联系管理员");
                }
                else
                {
                   // System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(ee.Result, UriKind.Relative), "_blank");
                   //(ee.Result);// new Uri(ee.Result, UriKind.Relative);
                    string uri = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;
                    //App.MessageBox.ShowDialog(uri);
                    if (!uri.ToLower().EndsWith("salary/"))
                    {
                        if(!uri.EndsWith("/'"))
                        {
                        uri = uri.Remove(uri.LastIndexOf('/') + 1) + ee.Result;
                        }
                    }
                    else
                    {
                        uri += ee.Result;
                    }
                    DownloadBtn.NavigateUri = new Uri(uri);
                    
                    DownloadBtn.Visibility = Visibility.Visible;
                }
               
            }
            catch(Exception ex)
            {

                App.MessageBox.ShowDialog("导出异常，"+ex.Message);
            }
        }

        /// <summary>
        /// 查询出数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Query4Btn_Click(object sender, RoutedEventArgs e)
        {

            if (CurrentTask == null
                || string.IsNullOrEmpty(SearchStartDPicker.Text)
                || string.IsNullOrEmpty(SearchEndDPicker.Text))
            {
                return;
            }

            if (DateTime.Parse(SearchStartDPicker.Text) >= DateTime.Parse(SearchEndDPicker.Text))
            {

                App.MessageBox.ShowDialog("开始日期应小于结束日期");
                return;
            }
            try
            {
                ServiceInstance.InforService.ExportInfoIntoStringAsync(CurrentTask.ID,
                       App.CurrentUser.UserID,
                       SearchStartDPicker.Text+" 00:00:00",
                       SearchEndDPicker.Text+" 23:59:59",100);

                exportLoading.Show();
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("提交失败，" + ex.Message);
            }

        }
        void InforService_ExportInfoIntoStringCompleted(object sender, ExportInfoIntoStringCompletedEventArgs e)
        {
            exportLoading.Stop();
            if (e.Result == null)
            {
                App.MessageBox.ShowDialog("查询的信息无效");
            }
            else
            {
                try
                {
                    Silverlight.DataTable table = Xml2Table.Convert(e.Result.TableNamek__BackingField,
                               e.Result._columns, e.Result.XmlStringk__BackingField);
                    if (table.Rows.Count == 0)
                    {
                        App.MessageBox.ShowDialog("没有查询到数据");
                        Grid3.ItemsSource = null;
                        return;
                    }
                    Grid3.ItemsSource = table.GetBindableData(new Silverlight.Connector());

                }
                catch (Exception ex)
                {
                    Grid3.ItemsSource = null;
                    App.MessageBox.ShowDialog("绑定数据失败，"+ex.Message);
                   
                }
            }
        }

        #endregion

        #region 任务配置

        void InitTaskConfigPage()
        {
            if (CurrentTask == null)
            {
                ConSearchStartDPicker.Text = DateTime.Now.ToShortDateString();
                ConSearchEndDPicker.Text = DateTime.Now.AddMonths(3).ToShortDateString();
                ConTaskNameTB.Text = string.Empty;
                TaskTitle3.Text = "请选择一个任务或新建一任务";

                ColMngPanel.Visibility = Visibility.Visible;
            }
        }

        private void AddColBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void DelColBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void UpBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void DownBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void UpdateBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void OKBtn_Click(object sender, RoutedEventArgs e)
        {

        }
       

      
       

        private void UpdateTaskBtn_Click(object sender, RoutedEventArgs e)
        {

        }

        private void CmitTaskBtn_Click(object sender, RoutedEventArgs e)
        {

        }

      

        private void NewTaskBtn_Click(object sender, RoutedEventArgs e)
        {

        }
        #endregion

    }
}
